<?php

namespace App\Console\Commands;

use App\Models\Product;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Psr\Log\NullLogger;

class CralwerCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cralwer';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $products = file_get_contents("products.txt");
        $products = explode("\n", $products);
        foreach ($products as $product) {
            try {
                if (!$product) {
                    continue;
                }

                $datas = [];
                $itemId = $product;
                $startTx = false;
                $product = Product::query()->where('item_id', $itemId)->first();
                if ($product) {
                    print_r('Product already exists ' . $itemId . "\n");
                    continue;
                }
                $skuInfo = $this->getItemSkuInfo($itemId);
                $hasImg = false;
                if (!empty($skuInfo['attr'])) {
                    foreach ($skuInfo['attr'][0]['attrValues'] as $item) {
                        if (isset($item['img']) && $item['img'] != '') {
                            $hasImg = true;
                        }
                    }
                }

                if ($hasImg) {
                    foreach ($skuInfo['attr'][0]['attrValues'] as $item) {
                        if (isset($item['img'])) {
                            $fileName = 'images/' . basename($item['img']);
                            $datas[] = [
                                'title' => $skuInfo['title'],
                                'price' => $skuInfo['price'],
                                'image' => $fileName,
                                'description' => '',
                                'description_image' => null,
                                'item_id' => $itemId
                            ];
                        }
                    }
                } else {
                    $this->saveImg($skuInfo['itemMainPic']);
                    $fileName = 'images/' . basename($skuInfo['itemMainPic']);
                    $productInfo = [
                        'title' => $skuInfo['title'],
                        'price' => $skuInfo['price'],
                        'image' => $fileName,
                        'description' => '',
                        'description_image' => null,
                        'item_id' => $itemId
                    ];

                    $productDetailInfo = [];

                    $detailDescs = $this->getDetailDesc($itemId);
                    foreach ($detailDescs as $detailDesc) {
                        if ($detailDesc['type'] == 2) {
                            $this->saveImg($detailDesc['url']);
                            $productDetailInfo[] = 'images/' . basename($detailDesc['url']);
                        }
                    }
                    $productInfo['description_image'] = $productDetailInfo;
                    $datas[] = $productInfo;

                }

                $startTx = true;
                DB::beginTransaction();
                foreach ($datas as $data) {
                    Product::query()->create($data);
                }

                DB::commit();

            } catch (\Exception $e) {
                if ($startTx) {
                    DB::rollBack();
                }
                print_r($itemId . $e->getFile() . "(" . $e->getLine() . ")" . $e->getMessage() . "\n");
            }

            sleep(2);
        }
        return 0;
    }


    public function getItemSkuInfo($itemId)
    {
        $res = Http::get('https://thor.weidian.com/detail/getItemSkuInfo/1.0', [
            'param' => json_encode(['itemId' => $itemId]),
            'wdtoken' => 'ed64fbd0',
            '_' => '1729155017602'
        ]);

        if ($res->successful()) {
            // 获取响应的 JSON 数据
            $data = $res->json();
            if ($data['status']['code'] == 0) {
                $data = $data['result'];
                return [
                    'price' => $data['itemDiscountHighPrice'] / 100,
                    'title' => $data['itemTitle'],
                    'attr' => $data['attrList'] ?? [],
                    'itemMainPic' => $data['itemMainPic']
                ];
            }
        } else {
            // 请求失败的处理
            print_r('Request failed', $res->status());
        }
    }


    public function getDetailDesc($itemId)
    {
        $res = Http::get('https://thor.weidian.com/detail/getDetailDesc/1.0', [
            'param' => json_encode(['vItemId' => $itemId]),
            'wdtoken' => 'ed64fbd0',
            '_' => '1729155017602'
        ]);

        if ($res->successful()) {
            // 获取响应的 JSON 数据
            $data = $res->json();
            if ($data['status']['code'] == 0) {
                return $data['result']['item_detail']['desc_content'];
            }
        } else {
            // 请求失败的处理
            print_r('Request failed', $res->status());
        }

    }


    public function saveImg($url)
    {
        //判断本地是否存在图片
        $fileName = basename($url);
        $path = 'images/' . $fileName;
        if (Storage::disk('public')->exists($path)) {
            print_r('Image already exists ' . $url . "\n");
            return;
        }

        $response = Http::get($url);
        if ($response->successful()) {
            // 获取图片的内容
            $imageContent = $response->body();

            // 定义保存的文件名
            $fileName = basename($url);

            // 将图片内容保存到 public 目录下的 images 文件夹
            Storage::disk('public')->put('images/' . $fileName, $imageContent);
            // 打印图片保存路径
            print_r('Image saved at: ' . Storage::url('images/' . $fileName) . ' ' . $url . "\n");
        } else {
            // 请求失败时处理
            print_r('Failed to download image', $response->status());
        }

    }


    public function fixImg()
    {
        $products = Product::query()->get();
        foreach ($products as $product) {
            // 如果 description_image 不为空
            if (!is_null($product->description_image)) {
                if (!is_array($product->description_image)) {
                    // 将 JSON 字符串解码为数组，再次编码时防止斜杠转义
                    $product->description_image = json_decode($product->description_image, true);
                    $product->save();  // 保存修改
                }

                $find = false;
                $imgs = [];
                foreach ($product->description_image as $key => $img) {
                    // 如果图片地址存在live 则删除保存
                    if (strpos($img, 'live-') === false) {
                        $imgs[] = $img;
                    } else {
                        $find = true;
                    }
                }

                if ($find) {
                    $product->description_image = $imgs;
                }

                $product->save();  // 保存修改
            }
        }
    }
}
